package com.结构型模式.组合模式;

import java.util.ArrayList;

/**
 * 物品
 * 抽象构件
 */
interface Articles{
    /**
     * 计算
     * @return
     */
    float calculation();

    /**
     * 显示
     */
    void show();
}

/**
 * 商品
 * 树叶构件
 */
class Goods implements Articles{
    private String name;//名称
    private int quantily; //数量
    private float unitprice;//单价
    Goods(String name,int quantily,float unitprice){
        this.name = name;
        this.quantily = quantily;
        this.unitprice = unitprice;
    }
    @Override
    public float calculation() {
        return unitprice * quantily;
    }

    @Override
    public void show() {
        System.out.println(String.format("名称：%s；" +
                "数量：%s;" +
                "单价：%s"
                ,name
                ,quantily
                ,unitprice));
    }
}

/**
 * 袋子
 * 树枝构件
 */
class Bags implements Articles{
    private String name;
    private ArrayList<Articles> bags = new ArrayList<>();
    Bags(String name){
        this.name = name;
    }
    void add(Articles c){
        bags.add(c);
    }
    void remove(Articles c){
        bags.remove(c);
    }
    Articles getChild(int i ){
        return bags.get(i);
    }

    @Override
    public float calculation() {
        float s  =  0;
        for(Object obj:bags){
            s = s + ((Articles)obj).calculation();
        }
        return s;
    }

    @Override
    public void show() {
        for(Object obj:bags){
            ((Articles)obj).show();
        }
    }
}
/**
 * 组合模式
 * 购物
 */
public class Combine {

    public static void main(String[] args) {
        float s  = 0 ;
        Bags  BigBag,mediumBag,smallRedBag,smallWhiteBag;
        Goods sp;
        BigBag = new Bags("大袋子");
        mediumBag = new Bags("中袋子");
        smallRedBag = new Bags("红色小袋子");
        smallWhiteBag = new Bags("白色小袋子");
        sp = new Goods("婺源特产",2,7.9f);
        smallRedBag.add(sp);
        sp = new Goods("婺源地图",1,9.9f);
        smallRedBag.add(sp);
        sp = new Goods("韶关红茶",3,180);
        smallRedBag.add(sp);
        sp = new Goods("景德镇瓷器",1,380);
        mediumBag.add(sp);
        mediumBag.add(smallRedBag);
        sp = new Goods("李宁运动鞋",1,198);
        BigBag.add(sp);
        BigBag.add(mediumBag);
        BigBag.add(smallWhiteBag);
        System.out.println("购物车：");
        BigBag.show();
        s  = BigBag.calculation();
        System.out.println(String.format("支付总价：%s",s));
    }
}
